<?php

namespace app\common\controller;

use app\common\utils\Constant;
use app\common\utils\WeChatUtils;
use app\index\logic\UserLogic;
use think\Config;
use think\Controller;
use think\Hook;
use think\Lang;

class Frontend extends Controller
{
    protected $user_id = 0;
    /**
     * 布局模板
     * @var string
     */
    protected $layout = '';

    public function _initialize()
    {
        parent::_initialize();
    }

    protected function check(){
        $token = $this->request->param('token');
        if(empty($token)){
            return $this->returnArray('token不能为空',false,Constant::CODE_ERROR);
        }
        $logic = new  UserLogic();
        $user_id = $logic->getUserIdByToken($token);
        if(!$user_id || empty($user_id)){
            return $this->returnArray('token失效',false,Constant::CODE_TOKEN_FAILURE);
        }
        $is_freeze = model('User')->where(array('id'=>$user_id))->value('is_freeze');
        if($is_freeze == 1){
            $module = strtolower($this->request->module());
            $controller = strtolower($this->request->controller());
            $method = $this->request->action();
            $url = "{$module}/{$controller}/{$method}";
            $node = model('FunctionNode')->where(array('url'=>$url))->find();
            if($node){
                $map['user_id'] = $user_id;
                $map['function_node_id'] = $node['id'];
                $count = model('UserNode')->where($map)->count();
                if($count && $count > 0){
                    return $this->returnArray('啊哦！防沉迷系统报告有异常，请联系客服处理。',false,Constant::CODE_ERROR);
                }
            }
        }
        return ['success'=>true,'user_id'=>$user_id];
    }

    protected function returnArray($msg='',$success=false,$code=1,$data=[]){
        return ['code'=>$code,'msg'=>$msg,'data'=>$data,'success'=>$success];
    }

    protected function returnJson($msg='',$code=1,$data=[]){
        return json(['code'=>$code,'msg'=>$msg,'data'=>$data]);
    }

    protected function getUserId(){
        $user = session('user');
        if(!$user || !isset($user)){
            return '';
        }
        return $user['id'];
    }

    /**
     * 加载语言文件
     * @param string $name
     */
    protected function loadlang($name)
    {
        Lang::load(APP_PATH . $this->request->module() . '/lang/' . Lang::detect() . '/' . str_replace('.', '/', $name) . '.php');
    }
    
    /**
     * 渲染配置信息
     * @param mixed $name 键名或数组
     * @param mixed $value 值 
     */
    protected function assignconfig($name, $value = '')
    {
        $this->view->config = array_merge($this->view->config ? $this->view->config : [], is_array($name) ? $name : [$name => $value]);
    }

    protected function jsSDK($url){
        $we_chat = Config::get('WeChat');
        $utils = new WeChatUtils($we_chat['app_id'], $we_chat['app_secret'], $we_chat['token']);
        $ticket = $utils->getJsApiTicket();
        $noncestr = $utils->getRandCode();//获取随机码
        $timestamp = time();//时间戳
        // 注意 URL 一定要动态获取，不能 hardcode.
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
//        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
//        $url = U('Home/WeChat/invite/'.$user['id']);
        $str = 'jsapi_ticket=' . $ticket . '&noncestr=' . $noncestr . '&timestamp=' . $timestamp . '&url='.$url;
        $signature = sha1($str);
        $data['host'] = "$protocol$_SERVER[HTTP_HOST]";
        $data['appId'] = $we_chat['app_id'];
        $data['ticket'] = $ticket;
        $data['noncestr'] = $noncestr;
        $data['timestamp'] = $timestamp;
        $data['signature'] = $signature;
        return $data;
    }

}
